"""
红外温度分析API客户端示例
演示如何使用Python调用温度分析API
"""

import requests
import json
import time


class ThermalAPIClient:
    """温度分析API客户端"""
    
    def __init__(self, base_url: str = "http://localhost:5000"):
        self.base_url = base_url.rstrip('/')
        self.session = requests.Session()
        
    def health_check(self):
        """健康检查"""
        response = self.session.get(f"{self.base_url}/api/health")
        return response.json()
        
    def start_stream(self, stream_url: str, fps_limit: int = 10):
        """启动视频流分析"""
        data = {
            "stream_url": stream_url,
            "fps_limit": fps_limit
        }
        response = self.session.post(f"{self.base_url}/api/start_stream", json=data)
        return response.json()
        
    def stop_stream(self):
        """停止视频流分析"""
        response = self.session.post(f"{self.base_url}/api/stop_stream")
        return response.json()
        
    def analyze_regions(self, regions):
        """分析区域温度"""
        data = {
            "regions": regions,
            "save_result": True
        }
        response = self.session.post(f"{self.base_url}/api/analyze_regions", json=data)
        return response.json()


def main():
    """示例主函数"""
    # 创建API客户端
    client = ThermalAPIClient("http://localhost:5000")
    
    try:
        # 1. 检查服务状态
        print("1. 检查API服务状态...")
        health = client.health_check()
        print(f"服务状态: {health['status']}")
        print(f"运行时间: {health['uptime_seconds']:.1f}秒")
        
        # 2. 启动视频流（使用测试URL）
        print("\n2. 启动视频流...")
        stream_result = client.start_stream("rtsp://test-stream-url", fps_limit=15)
        print(f"启动结果: {stream_result['message']}")
        
        # 3. 等待一段时间让流连接
        print("等待流连接...")
        time.sleep(2)
        
        # 4. 分析区域温度
        print("\n3. 分析区域温度...")
        regions = [
            {"x1": 100, "y1": 100, "x2": 300, "y2": 300},
            {"x1": 400, "y1": 200, "x2": 600, "y2": 400}
        ]
        
        analysis_result = client.analyze_regions(regions)
        
        if analysis_result['success']:
            print(f"分析成功: {analysis_result['message']}")
            print(f"分析时间: {analysis_result['analysis_time']}")
            
            # 打印每个区域的结果
            for region in analysis_result['regions']:
                stats = region['temperature_stats']
                print(f"\n区域{region['region_id']}:")
                print(f"  坐标: ({region['coordinates']['x1']}, {region['coordinates']['y1']}) "
                      f"到 ({region['coordinates']['x2']}, {region['coordinates']['y2']})")
                print(f"  最高温: {stats['max_temp']:.1f}°C "
                      f"位置: ({stats['max_position']['x']}, {stats['max_position']['y']})")
                print(f"  最低温: {stats['min_temp']:.1f}°C "
                      f"位置: ({stats['min_position']['x']}, {stats['min_position']['y']})")
                print(f"  平均温: {stats['avg_temp']:.1f}°C")
                print(f"  温度差: {stats['temp_diff']:.1f}°C")
                print(f"  像素数: {stats['pixel_count']}")
        else:
            print(f"分析失败: {analysis_result['message']}")
        
        # 5. 停止视频流
        print("\n4. 停止视频流...")
        stop_result = client.stop_stream()
        print(f"停止结果: {stop_result['message']}")
        
    except requests.exceptions.ConnectionError:
        print("无法连接到API服务器，请确保服务器已启动")
        print("启动命令: python start_api.py")
    except Exception as e:
        print(f"发生错误: {e}")


if __name__ == '__main__':
    main()